package com.ruoyi.framework.web.service;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.WechatConfig;
import com.ruoyi.framework.web.domain.TemplateMsgEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class TemplateService {

    private String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";

    private final WechatConfig wechatConfig;

    public String getAccessToken() {
        String requestUrl = accessTokenUrl + "appid=" + wechatConfig.getAppId() + "&secret=" + wechatConfig.getAppKey();
        String resp = HttpUtil.get(requestUrl);
        JSONObject result = JSONUtil.parseObj(resp);
        log.info("获取access_token:" + resp);
        return result.getStr("access_token");
    }

    public JSONObject sendMsg(TemplateMsgEntity messageVo, String token, String openId) {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="  + token;
        Map<String,Object> content=new HashMap<>();
        JSONObject data = JSONUtil.createObj();
        data.put("thing19",new JSONObject().put("value",messageVo.getThing19()));
        data.put("thing2",new JSONObject().put("value",messageVo.getThing2()));
        data.put("time4",new JSONObject().put("value",messageVo.getTime4()));
        data.put("phrase3",new JSONObject().put("value",messageVo.getPhrase3()));
        data.put("thing14",new JSONObject().put("value",messageVo.getThing14()));

        content.put("touser",openId);
        content.put("template_id",wechatConfig.getTemplateId());
        content.put("data",data);
        String resp = HttpUtil.post(requestUrl,JSONUtil.parse(content).toString());
        JSONObject result = JSONUtil.parseObj(resp);
        log.info("发送内容：{}", JSON.toJSONString(data));
        log.info("发送响应数据：{}",resp);
        return result;
    }
}
